$(function(){
	drawBoard();
});

var moveCount = 0;
var WHITE = 9999;
var BLACK = 6666;
var currentPlayer = WHITE;
var userColor = WHITE;//white 0 black


var WHITE_PAWN 		= 1;
var WHITE_KNIGHT 	= 2;
var WHITE_KING 		= 3;
var WHITE_BISHOP 	= 4;
var WHITE_ROOK 		= 5;
var WHITE_QUEEN 	= 6;

var BLACK_PAWN 		= -WHITE_PAWN;
var BLACK_KNIGHT 	= -WHITE_KNIGHT;
var BLACK_KING 		= -WHITE_KING;
var BLACK_BISHOP 	= -WHITE_BISHOP;
var BLACK_ROOK 		= -WHITE_ROOK;
var BLACK_QUEEN 	= -WHITE_QUEEN;

var board = 
	[
		[BLACK_ROOK, BLACK_KNIGHT, BLACK_BISHOP, BLACK_QUEEN, BLACK_KING, BLACK_BISHOP, BLACK_KNIGHT, BLACK_ROOK],
		[BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[0,0,0,0,0,0,0,0],
		[WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN],
		[WHITE_ROOK, WHITE_KNIGHT, WHITE_BISHOP, WHITE_QUEEN, WHITE_KING, WHITE_BISHOP, WHITE_KNIGHT, WHITE_ROOK]
	];

function drawBoard()
{
	var htmlStr = "";
	for(var i=0; i<8; i++){
		for(var j=0; j<8; j++){
			htmlStr += "<div class='cell " + ((i+j)%2 == 0 ? "" : "dark") + "'>" + "<div class='" + getPieceName(board[i][j]) + "'" + "data='" + (i*8+j) + "'" + "></div>" + "</div>";

		}
	}
	$("#board").html(htmlStr);
	
	$(".cell div").filter(function(){
        return $(this).attr('class').indexOf(userColor ? 'WHITE' : 'BLACK') !== -1 && currentPlayer == userColor;
    }).draggable({ revert: 'invalid' });
	
	$(".cell div").droppable({
		drop: function( event, ui ) {
		$( this )
			var from = ui.draggable.parent().find('div').attr('data');
			var to = parseInt($(this).attr('data'));
			var pieceName = $(this).attr('class').split(" ")[0];
			var validsCells = getValidCell(from);
			if(validsCells.indexOf(to) != -1){
				var iFrom = Math.floor(from/8);
				var jFrom = from%8;
				var iTo = Math.floor(to/8);
				var jTo = to%8;
				board[iTo][jTo] = board[iFrom][jFrom];
				board[iFrom][jFrom] = 0;
			}
			drawBoard();
		}
	});
	
	$(".cell div").mousedown(function(){
		var from = parseInt($(this).attr('data'));
		var pieceName = $(this).attr('class').split(" ")[0];
		writeLog("from " + from + " name = " + pieceName);
		var validCells = getValidCell(from);
		removehightlightedCells();
		hightlightCells(validCells);
	});
}

function removehightlightedCells(){
	$("div[class*='hightlight']").removeClass("hightlight");
}

function hightlightCells(cells){
	for(var i=0; i<cells.length; i++){
		var element = "div[data='" + cells[i] + "']";
		var e = $(element);
		$(element).parent().addClass("hightlight");
	}
}

function getValidCell(from){
	var row = Math.floor(from/8);
	var col = from%8;
	var pieceName = getPieceName(board[row][col]);
	var validCells = new Array();
	if(pieceName.indexOf("KING") != -1){
		validCells = getValidKingCellMove(row, col);
	}else if(pieceName.indexOf("QUEEN") != -1){
		validCells = getValidQueenCellMove(row, col);
	}else if(pieceName.indexOf("BISHOP") != -1){
		validCells = getValidBishopCellMove(row, col);
	}else if(pieceName.indexOf("KNIGHT") != -1){
		validCells = getValidKnightCellMove(row, col);
	}else if(pieceName.indexOf("PAWN") != -1){
		validCells = getValidPawnCellMove(row, col);
	}else if(pieceName.indexOf("ROOK") != -1){
		validCells = getValidRookCellMove(row, col);
	}
	return validCells;
}

function getValidKnightCellMove(row, col){
	var directionIndices = [[-2, -2,  2, 2, 1, -1, 1, -1],
							[-1,  1, -1, 1, -2, -2, 2, 2]];

	return getCellsWithDirectionIndicesNoStartArround(row, col, directionIndices)
}

function getValidPawnCellMove(row, col){
	var directionIndices = [[-1, -1, -1],[-1, 1, 0]];

	if(isPawnFirstMove(row, col)){
		directionIndices[0][directionIndices[0].length] = -2;
		directionIndices[1][directionIndices[1].length] = 0;
	}

	return getPawnCellsWithDirectionIndices(row, col, directionIndices);
}

function isPawnFirstMove(row, col){
	if(row == 6)
		return true;
	return false;
}

function getValidQueenCellMove(row, col){
	var rookCells = getValidRookCellMove(row, col);
	var bishopCells = getValidBishopCellMove(row, col);

	return mergeTwoArrays(rookCells, bishopCells);
}

function getCellsWithDirectionIndices(row, col, directionIndices, startSizeArround){
	var validCells = new Array();

	do{
		var newRow = -1;
		var newCol = -1;
		var removeDirectionIndices = new Array();
		for(var i=0; i<directionIndices[0].length; i++){
			newRow = row + directionIndices[0][i]*startSizeArround;
			newCol = col + directionIndices[1][i]*startSizeArround;

			if(!isValidCell(newRow, newCol) || cellContainOwnPiece(newRow, newCol)){
				removeDirectionIndices[removeDirectionIndices.length] = i;
				continue;
			}

			validCells[validCells.length] = newRow*8 + newCol;

			if(cellContainOpponentPiece(newRow, newCol)){
				removeDirectionIndices[removeDirectionIndices.length] = i;
			}

		}

		for(var i=removeDirectionIndices.length - 1; i >= 0; i--){
			directionIndices[0].splice(removeDirectionIndices[i], 1);
			directionIndices[1].splice(removeDirectionIndices[i], 1);
		}
		startSizeArround++;
	}while(directionIndices[0].length != 0);

	return validCells;
}

function getCellsWithDirectionIndicesNoStartArround(row, col, directionIndices){
	var validCells = new Array();

	var newRow = -1;
	var newCol = -1;

	for(var i=0; i<directionIndices[0].length; i++){

		newRow = row + directionIndices[0][i];
		newCol = col + directionIndices[1][i];

		if(!isValidCell(newRow, newCol) || cellContainOwnPiece(newRow, newCol)){
			continue;
		}

		validCells[validCells.length] = newRow*8 + newCol;
	}

	return validCells;
}

function getPawnCellsWithDirectionIndices(row, col, directionIndices){
	var validCells = new Array();

	var newRow = -1;
	var newCol = -1;

	for(var i=0; i<directionIndices[0].length; i++){
		// if(directionIndices[0][i] == 0 && directionIndices[1][i] == 0)
		// 	continue;

		newRow = row + directionIndices[0][i];
		newCol = col + directionIndices[1][i];

		if(!isValidCell(newRow, newCol) || cellContainOwnPiece(newRow, newCol)){
			continue;
		}

		if(i == 0 || i == 1){
			if(!cellContainOpponentPiece(newRow, newCol)){
				continue;
			}
		}

		validCells[validCells.length] = newRow*8 + newCol;
	}

	return validCells;
}

function getValidRookCellMove(row, col){
	var validCells = new Array();
	var directionIndices = [[-1, 0, 1, 0],[0, 1, 0, -1]];

	var startSizeArround = 1;
	return getCellsWithDirectionIndices(row, col, directionIndices, startSizeArround);
}

function getValidBishopCellMove(row, col){
	var validCells = new Array();
	var directionIndices = [[-1, 1, 1, -1],[1, 1, -1, -1]];

	var startSizeArround = 1;
	return getCellsWithDirectionIndices(row, col, directionIndices, startSizeArround);
}

function cellContainOwnPiece(row, col){
	if(board[row][col] > 0){
		return true;
	}
	return false;
}

function isValidCell(row, col){
	if(row >= 0 && row < 8)
		if(col >= 0 && col < 8)
			return true;

	return false;
}

function cellContainOpponentPiece(row, col){
	if(board[row][col] < 0){
		return true;
	}
	return false;
}

function getValidKingCellMove(row, col){
	var directionIndices = [[-1, -1, 0, 1, 1, 1, 0, -1],[0, 1, 1, 1, 0, -1, -1, -1]];
	
	var validCells = new Array();

	for(var i=0; i<directionIndices[0].length; i++){
			var newRow = row + directionIndices[0][i];
			var newCol = col + directionIndices[1][i];
			if(isValidCell(newRow, newCol) && !cellContainOwnPiece(newRow, newCol)){
				validCells[validCells.length] = newRow * 8 + newCol;
			}
		
	}
	
	return validCells;
}

function getPieceValue(pieceName){
	if(pieceName == "WHITE_KING"){
		return WHITE_KING;
	}else if(pieceName == "WHITE_QUEEN"){
		return WHITE_QUEEN;
	}else if(pieceName == "WHITE_BISHOP"){
		return WHITE_BISHOP;
	}else if(pieceName == "WHITE_KNIGHT"){
		return WHITE_KNIGHT;
	}else if(pieceName == "WHITE_PAWN"){
		return WHITE_PAWN;
	}else if(pieceName == "WHITE_ROOK"){
		return WHITE_ROOK;
	}else if(pieceName == "BLACK_KING"){
		return BLACK_KING;
	}else if(pieceName == "BLACK_QUEEN"){
		return BLACK_QUEEN;
	}else if(pieceName == "BLACK_BISHOP"){
		return BLACK_BISHOP;
	}else if(pieceName == "BLACK_KNIGHT"){
		return BLACK_KNIGHT;
	}else if(pieceName == "BLACK_PAWN"){
		return BLACK_PAWN;
	}else if(pieceName == "BLACK_ROOK"){
		return BLACK_ROOK;
	}
	return 0;
}

function getPieceName(pieceValue){
    switch (pieceValue) {
        case WHITE_KING: return 'WHITE_KING';
        case WHITE_QUEEN: return 'WHITE_QUEEN';
        case WHITE_ROOK: return 'WHITE_ROOK';
        case WHITE_BISHOP: return 'WHITE_BISHOP';
        case WHITE_KNIGHT: return 'WHITE_KNIGHT';
        case WHITE_PAWN: return 'WHITE_PAWN';
        
        case BLACK_KING: return 'BLACK_KING';
        case BLACK_QUEEN: return 'BLACK_QUEEN';
        case BLACK_ROOK: return 'BLACK_ROOK';
        case BLACK_BISHOP: return 'BLACK_BISHOP';
        case BLACK_KNIGHT: return 'BLACK_KNIGHT';
        case BLACK_PAWN: return 'BLACK_PAWN';
        
        default: return 'EMPTY';
    }
}
